package com.aispeech.asr.comm.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.nio.file.Path;

@Slf4j
public class PCMUtils {
    public static long calcDuration(Path originPCMPath, int sampleRate, int sampleBytes) {
        File originPCM = originPCMPath.toFile();
        int bytesPerMsecs = sampleRate * sampleBytes / 1000;

        if (originPCM != null && originPCM.exists()) {
            return originPCM.length() / bytesPerMsecs;
        } else {
            log.error("[ calcDuration ] origin pcm not exists. path: {}", originPCMPath.toAbsolutePath());
            return -1L;
        }
    }

    public static long pcmBytesToMsecs(long offset, int sampleRate, int channel, int sampleBytes) {
        return offset * 1000 / (sampleRate * channel * sampleBytes);
    }

    public static long pcmMsecsToBytes(long duration, int sampleRate, int channel, int sampleBytes) {
        return duration * sampleRate * channel * sampleBytes / 1000;
    }
}
